/*
 * Copyright (C) 2008 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.hisense.settings;

import com.android.settings.R;
import android.content.ContentResolver;
import android.content.Context;
import android.database.ContentObserver;
import android.os.Bundle;
import android.os.Handler;
import android.os.IPowerManager;
import android.os.Parcel;
import android.os.Parcelable;
import android.os.RemoteException;
import android.os.ServiceManager;
import android.preference.SeekBarPreference;
import android.provider.Settings;
import android.provider.Settings.SettingNotFoundException;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.SeekBar;
import android.widget.TextView;
import android.preference.SeekBarDialogPreference;

import android.preference.PreferenceScreen;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import android.content.SharedPreferences.OnSharedPreferenceChangeListener;
import android.os.ServiceManager;
import android.media.AudioManager;


import java.util.List;
import android.util.Log;


public class PowerOnSoundPreference extends SeekBarDialogPreference implements
        SeekBar.OnSeekBarChangeListener{
    
    private static final String TAG = "PowerOnSoundPreference";

	public static final String KEY_POWER_ON_SOUND = "power_on_sound";
    private SeekBar mSeekBar;

    private int mOldSound;

    private boolean mRestoredOldState;

    // Balance range is from -10 - 10. Need to make sure that user
    // doesn't set the soundValue to 0 and get stuck
    private static final int MINIMUM_VALUE = 0;
    private static final int MAXIMUM_VALUE = 100;
    private TextView textview_sound;

	private int currentVolume;
	private int currentSeekbarValue;
	SharedPreferences.Editor editor;
	private AudioManager mAudioManager;
	private int saveVolume;
    
    private ContentObserver mBalanceObserver = new ContentObserver(new Handler()) {
        @Override
        public void onChange(boolean selfChange) {
            onSoundChanged();
        }
    };


    public PowerOnSoundPreference(Context context, AttributeSet attrs) {
        super(context, attrs);
        setDialogLayoutResource(R.layout.preference_dialog_power_on_sound);         
    }

    @Override
    protected void showDialog(Bundle state) {
        super.showDialog(state);
        mRestoredOldState = false;
    }

    @Override
    protected void onBindDialogView(View view) {
        super.onBindDialogView(view);

		mAudioManager = (AudioManager)getContext().getSystemService(Context.AUDIO_SERVICE);
		//current TV volume,exit seekbar restore it
		currentVolume = mAudioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
		//show seekbar value,defaule 30
		currentSeekbarValue = Settings.Secure.getInt(getContext().getContentResolver(),
                    "settings_power_sound_value",30);

        //mSeekBar = getSeekBar(view);
        mSeekBar = (SeekBar)view.findViewById(R.id.power_on_sound_seekbar);

        mSeekBar.setMax(MAXIMUM_VALUE - MINIMUM_VALUE);
		mSeekBar.setKeyProgressIncrement(1);
        mOldSound = currentSeekbarValue;
        mSeekBar.setProgress(mOldSound - MINIMUM_VALUE);
        mSeekBar.setOnSeekBarChangeListener(this);
        
        textview_sound = (TextView)view.findViewById(R.id.power_on_sound_textview);
        textview_sound.setText("" + mOldSound);
		saveVolume = currentSeekbarValue;
		
		Log.d(TAG, "saveVolume:" + saveVolume);

    }

    public void onProgressChanged(SeekBar seekBar, int progress,
            boolean fromTouch) {
		saveVolume = progress;
		Log.d(TAG, "progress:" + progress);
		
		//not change current volume,only change the data by zhengqingqing
//		mAudioManager.setStreamVolume(AudioManager.STREAM_MUSIC, 
//					progress, AudioManager.FLAG_PLAY_SOUND);	
        
        textview_sound.setText("" + (progress + MINIMUM_VALUE));
    }

    public void onStartTrackingTouch(SeekBar seekBar) {
        // NA
    }

    public void onStopTrackingTouch(SeekBar seekBar) {
        // NA
    }

    private int getPowerOnSound(int defaultValue) {
        int soundValue = defaultValue;
        
        // TODO 
        
        return soundValue;
    }


    private void onSoundChanged() {
        //int soundValue = getPowerOnSound(MAXIMUM_VALUE);
        //mSeekBar.setProgress(soundValue - MINIMUM_VALUE);
    }

    @Override
    protected void onDialogClosed(boolean positiveResult) {
        super.onDialogClosed(positiveResult);

        final ContentResolver resolver = getContext().getContentResolver();

        if (positiveResult) {
			//Restore old volume;save power on sound
			mAudioManager.setStreamVolume(AudioManager.STREAM_MUSIC, 
					currentVolume, AudioManager.FLAG_PLAY_SOUND);	
			Settings.Secure.putInt(resolver,
                    "settings_power_sound_value", saveVolume);
			Log.d(TAG, saveVolume+"saveVolume-->currentVolume:" + currentVolume);
        } else {
        	//Restore old volume;Restore old power on sound value
            restoreOldState();

        }
        Log.d(TAG, "onDialogClosed-->positiveResult" + positiveResult);
        resolver.unregisterContentObserver(mBalanceObserver);
    }

    private void restoreOldState() {
        if (mRestoredOldState) return;
		mAudioManager.setStreamVolume(AudioManager.STREAM_MUSIC, 
					currentVolume, AudioManager.FLAG_PLAY_SOUND);	
        mRestoredOldState = true;
    }


    @Override
    protected Parcelable onSaveInstanceState() {
        final Parcelable superState = super.onSaveInstanceState();
        if (getDialog() == null || !getDialog().isShowing()) return superState;

        // Save the dialog state
        final SavedState myState = new SavedState(superState);
        myState.progress = mSeekBar.getProgress();
        myState.oldProgress = mOldSound;

        // Restore the old state when the activity or dialog is being paused
        restoreOldState();
        Log.d(TAG, "onSaveInstanceState-->myState=" + myState);
        return myState;
    }

    @Override
    protected void onRestoreInstanceState(Parcelable state) {
        if (state == null || !state.getClass().equals(SavedState.class)) {
            // Didn't save state for us in onSaveInstanceState
            super.onRestoreInstanceState(state);
            Log.d(TAG, "onRestoreInstanceState-->myState=" + state);
            return;
        }

        SavedState myState = (SavedState) state;
        super.onRestoreInstanceState(myState.getSuperState());
        mOldSound = myState.oldProgress;
        //setPowerOnSound(myState.progress + MINIMUM_VALUE);
        //setPowerOnSound(String.valueOf(myState.progress + MINIMUM_VALUE));
    }

    private static class SavedState extends BaseSavedState {

        int progress;
        int oldProgress;

        public SavedState(Parcel source) {
            super(source);
            progress = source.readInt();
            oldProgress = source.readInt();
        }

        @Override
        public void writeToParcel(Parcel dest, int flags) {
            super.writeToParcel(dest, flags);
            dest.writeInt(progress);
            dest.writeInt(oldProgress);
        }

        public SavedState(Parcelable superState) {
            super(superState);
        }

        public static final Parcelable.Creator<SavedState> CREATOR =
                new Parcelable.Creator<SavedState>() {

            public SavedState createFromParcel(Parcel in) {
                return new SavedState(in);
            }

            public SavedState[] newArray(int size) {
                return new SavedState[size];
            }
        };
    }
}

